#include "gamefield.h"

GameField::GameField(const QPixmap & pixmap, QGraphicsItem * parent) : QGraphicsItem(parent), m_pixmap(pixmap), m_putTower(0)
{
    setAcceptsHoverEvents(true);
}

QRectF GameField::boundingRect() const
{
    return QRectF(0, 0, m_pixmap.width(), m_pixmap.height());
}

void GameField::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    painter->save();
    painter->drawPixmap(QRectF(0 ,0, m_pixmap.width(), m_pixmap.height()), m_pixmap, QRectF());
    painter->restore();
}

void GameField::startUnit(UnitItem * unit)
{
    unit->setWaypoints(m_waypoints);
    unit->setScale(scale());

    QSequentialAnimationGroup *group = new QSequentialAnimationGroup;

    for (int i = 0; i < m_waypoints.count() - 1; i++)
    {
        Animation * m_anim = new Animation(unit, group);
        QPoint w1 = m_waypoints.at(i) * unit->scale();
        QPoint w2 = m_waypoints.at(i + 1) * unit->scale();
        m_anim->setStartValue(w1);
        m_anim->setEndValue(w2);
        /*
          duration = (ideal_time / unit_speed) * (lengthWaypoint[i] / lengthWaypoints)
          default speed ~= 40 sec
          */
        m_anim->setDuration(  (20000 / (unit->unitProperties().speed / 100)) * (m_lengthWaypoint.at(i) / m_lengthWaypoints)  );
        group->addAnimation(m_anim);
    }
    group->start();
    QObject::connect(group, SIGNAL(finished()), unit, SLOT(deleteLater()));
}

void GameField::setWaypoints(const Waypoints & ways)
{
    m_waypoints = ways;
    calcWaypointsLength();
}

void GameField::calcWaypointsLength()
{
    m_lengthWaypoints = 0;
    m_lengthWaypoint.clear();
    for (int i = 1; i < m_waypoints.count(); i++)
    {
        qreal l = sqrt(pow(m_waypoints.at(i).x() - m_waypoints.at(i-1).x(), 2) + pow(m_waypoints.at(i).y() - m_waypoints.at(i-1).y(), 2) );
        m_lengthWaypoint << l;
        m_lengthWaypoints +=l;
    }
}

void GameField::putTower(TowerItem * tower)
{
    m_putTower = tower;
}

void GameField::cancelPutTower()
{
    delete m_putTower;
    m_putTower = 0;
}

void GameField::hoverMoveEvent(QGraphicsSceneHoverEvent *event)
{
      if (m_putTower)
      {
          // hide cursor and move tower
          setCursor(Qt::BlankCursor);
      }
      else
      {
          setCursor(Qt::ArrowCursor);
      }
}
